﻿using System.Collections.Generic;

using UnityEngine;

namespace YuoTools
{
    public class SoundManger : SingletonMono<SoundManger>
    {
        [Header("正在播放的AudioSource")]
        [BackgroundColor(0, 0, 0.8f, 0.5f)]
        public List<AudioSource> Sounds = new List<AudioSource>();
        [Header("休眠的AudioSource")]
        [BackgroundColor(0, 0.5f, 1, 0.5f)]
        public List<AudioSource> SoundPools = new List<AudioSource>();
        [Header("背景音效")]
        [BackgroundColor(0.3f, 0.5f, 1, 0.5f)]
        public AudioSource Bg;
        [Header("最大缓存Source数量")]
        [BackgroundColor(0.3f, 0.5f, 1, 0.5f)]
        public int MaxSourceNum = 8;
        float BgValue = 1;
        float SoundValue = 1;
        List<YuoDelayMod> AllDelay = new List<YuoDelayMod>();
        public override void Awake()
        {
            base.Awake();
            DontDestroyOnLoad(gameObject);
            Bg = gameObject.AddComponent<AudioSource>();
            Bg.playOnAwake = false;
        }
        public void PlaySound(AudioClip clip, float value = 1)
        {
            if (clip == null) return;
            AudioSource asTemp;
            if (SoundPools.Count > 0)
            {
                asTemp = SoundPools[0];
                SoundPools.Remove(asTemp);
            }
            else
            {
                asTemp = gameObject.AddComponent<AudioSource>();
            }
            asTemp.clip = clip;
            asTemp.loop = false;
            asTemp.playOnAwake = false;
            asTemp.volume = SoundValue * value;
            asTemp.Play();
            Sounds.Add(asTemp);
            AllDelay.Add(
            this.YuoDelayRealtime(mod =>
            {
                asTemp.Stop();
                Sounds.Remove(asTemp);
                SoundPools.Add(asTemp);
                AllDelay.Remove(mod);
            }, clip.length).SetName(clip.name));
        }
        public void StopAllSound()
        {
            for (int i = 0; i < Sounds.Count;)
            {
                Sounds[0].Stop();
                SoundPools.Add(Sounds[0]);
                Sounds.RemoveAt(0);
            }
            foreach (var item in AllDelay)
            {
                YuoDelayCon.Instance.StopForce(item);
            }
            MaxSourceNum.Clamp();
            if (SoundPools.Count > MaxSourceNum)
            {
                for (int i = MaxSourceNum; i < SoundPools.Count;)
                {
                    Destroy(SoundPools[i]);
                    SoundPools.RemoveAt(MaxSourceNum);
                }
            }
            AllDelay.Clear();
        }
        public void PlayBg(AudioClip clip, float value = 1, bool Loop = true)
        {
            if (Bg.clip != clip)
            {
                Bg.clip = clip;
                Bg.Play();
            }
            Bg.loop = Loop;
            Bg.volume = BgValue * value;
        }
    }
}
